package com.bluepunch.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bluepunch.entity.User;
import com.bluepunch.service.UserInfoService;
import com.bluepunch.service.UserService;
import com.bluepunch.utils.MessageUtils;
import com.bluepunch.vo.RegisterForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @Autowired
    UserInfoService userInfoService;

    @GetMapping({"/", "/index"})
    public String index() {
        return "index";
    }

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @GetMapping("/register")
    public String toRegister() {
        return "register";
    }

    //注册业务
    @PostMapping("/register")
    public String register(RegisterForm registerForm, Model model) {
        MessageUtils.print("注册表单信息：" + registerForm.toString());

        // 表单密码重复判断
        if (!registerForm.getPassword().equals(registerForm.getRepassword())) {
            model.addAttribute("registerMsg", "密码输入有误");
            return "register";
        }

        // 用户名已存在
        User hasUser = userService.getOne(new QueryWrapper<User>().eq("username", registerForm.getUsername()));
        if (hasUser != null) {
            model.addAttribute("registerMsg", "用户名已存在");
            return "register";
        }

        //构建用户对象
        User user = new User();
        user.setUserId(MessageUtils.getUuid());
        user.setUsername(registerForm.getUsername());
        user.setState(1);
        user.setRealId("4");

        // 密码加密
        String bCryptPassword = new BCryptPasswordEncoder().encode(registerForm.getPassword());
        user.setPassword(bCryptPassword);

        // 保存对象
        userService.save(user);
        MessageUtils.print("新用户注册成功：" + user);

        return "redirect:/toLogin";
    }
}

